package com.pinxixi.auth.controller;

import com.alibaba.fastjson.JSON;
import com.pinxixi.auth.service.AuthService;
import com.pinxixi.framework.domain.ucenter.AuthToken;
import com.pinxixi.framework.domain.ucenter.UserExt;
import com.pinxixi.framework.model.response.CommonCode;
import com.pinxixi.framework.model.response.QueryResponseResult;
import com.pinxixi.framework.model.response.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author Administrator
 * @version 1.0
 **/
@RestController
@RequestMapping("/")
@CrossOrigin(origins = "*")
public class AuthController {

    @Value("${auth.clientId}")
    String clientId;
    @Value("${auth.clientSecret}")
    String clientSecret;
    @Autowired
    AuthService authService;

    @PostMapping("/userlogin")
    public ResponseResult login(@RequestBody UserExt user, HttpServletResponse response, HttpServletRequest request) {
        //账号
        String username = user.getUsername();
        //密码
        String password = user.getPassword();
        //申请令牌
        AuthToken authToken =  authService.login(username,password,clientId,clientSecret);
        //用户身份令牌
        String access_token = authToken.getAccess_token();

        Cookie cookie = new Cookie("token",access_token);
        cookie.setPath("/");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.addCookie(cookie);

        return new QueryResponseResult(CommonCode.SUCCESS,access_token);
    }

    @GetMapping("/userlogout")
    public ResponseResult logout(HttpServletResponse response){
        Cookie cookie = new Cookie("token","");
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.addCookie(cookie);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    @PostMapping("/userjwt")
    public QueryResponseResult exchange(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Jwt decode = JwtHelper.decode(token);
        String claims = decode.getClaims();
        Map map = JSON.parseObject(claims, Map.class);
        return new QueryResponseResult(CommonCode.SUCCESS,map);
    }

}
